package com.henu.engineer.controller.teacher.pl

import com.alibaba.fastjson.JSONObject
import com.henu.engineer.StringUtils
import com.henu.engineer.service.FileService
import com.henu.engineer.service.LoginService
import com.henu.engineer.service.UserService
import com.henu.engineer.service.UserService.Companion.logger
import com.henu.engineer.service.teacher.CourseGroupService
import com.henu.engineer.service.teacher.pro.CultivatingGoalPLService
import org.apache.commons.io.FileUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.util.ClassUtils
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.io.IOException
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter


/**
 * @author noexcept
 * @since 9/25/2021 6:29 PM
 */
@RestController
@RequestMapping("pl")
class CultivatingProjectPLController {

    @Autowired
    lateinit var loginService: LoginService



    @Autowired
    lateinit var cultivatingGoalPLService: CultivatingGoalPLService

    @Autowired
    lateinit var fileService:FileService

    @Autowired
    lateinit var courseGroupService:CourseGroupService




    @DeleteMapping("/cultivatingGoal")
    fun delCultivatingGoal(id: Int?): String {
        val res = JSONObject()
        if (id==null) {
            res["code"] = 1
            res["msg"] = "id参数缺失"
            return res.toJSONString()
        }

        if (cultivatingGoalPLService.delCultivatingGoal(id!!)) {
            res["code"] = 0
            res["msg"] = "success"
        } else {
            res["code"] = 2
            res["msg"] = "fail"
        }
        return res.toJSONString()
    }

    @PatchMapping("/cultivatingGoal")
    fun updateCultivatingGoal(id: Int?, content: String?): String {
        val res = JSONObject()
        if (StringUtils.isEmpty(content)||id==null) {
            res["code"] = 1
            res["msg"] = "id或content参数缺失"
            return res.toJSONString()
        }

        if (cultivatingGoalPLService.updateCultivatingGoal(id!!, content!!)) {
            res["code"] = 0
            res["msg"] = "success"
        } else {
            res["code"] = 2
            res["msg"] = "fail"
        }
        return res.toJSONString()
    }

    /**
     * @param version yyyy-MM-dd
     */
    @PostMapping("/cultivatingGoal")
    fun addCultivatingGoal(@RequestBody jsonObject: JSONObject?): String {
        val res = JSONObject()
        if (jsonObject == null) {
            res["code"] = 1
            res["msg"] = "specialization,version或content参数缺失"
            return res.toJSONString()
        }
        val specialization = jsonObject["specialization"] as String?
        val version = jsonObject["version"] as String?
        val content = jsonObject["content"] as String?
        if (StringUtils.isEmpty(specialization, version, content)) {
            res["code"] = 1
            res["msg"] = "specialization,version或content参数缺失"
            return res.toJSONString()
        }
        val localDate: LocalDate?
        try {
            localDate = LocalDate.parse(version)
        } catch (e: Exception) {
            res["code"] = 2
            res["msg"] = "version格式解析异常"
            return res.toJSONString()
        }

        return if (cultivatingGoalPLService.addCultivatingGoal(specialization!!, localDate, content!!)) {
            res["code"] = 0
            res["msg"] = "success"
            res.toJSONString()
        } else {
            res["code"] = 3
            res["msg"] = "fail"
            res.toJSONString()
        }
    }

    /**
     * 毕业要求部分
     */


    @DeleteMapping("/gr")
    fun delGraduationRequirement(id: Int?): String {
        val res = JSONObject()
        if (id==null) {
            res["code"] = 1
            res["msg"] = "id参数缺失"
            return res.toJSONString()
        }

        if (cultivatingGoalPLService.delGraduationRequirement(id!!)) {
            res["code"] = 0
            res["msg"] = "success"
        } else {
            res["code"] = 2
            res["msg"] = "fail"
        }
        return res.toJSONString()
    }

    @PatchMapping("/gr")
    fun updateGraduationRequirement(id: Int?, name: String?, content: String?): String {
        val res = JSONObject()
        if (StringUtils.isEmpty(name, content)||id==null) {
            res["code"] = 1
            res["msg"] = "id,name或content参数缺失"
            return res.toJSONString()
        }

        if (cultivatingGoalPLService.updateGraduationRequirement(id!!, name!!, content!!)) {
            res["code"] = 0
            res["msg"] = "success"
        } else {
            res["code"] = 2
            res["msg"] = "fail"
        }
        return res.toJSONString()
    }

    @PostMapping("/gr")
    fun addGraduationRequirement(@RequestBody jsonObject: JSONObject?): String {
        val res = JSONObject()
        if (jsonObject == null) {
            res["code"] = 1
            res["msg"] = "specialization,version或content参数缺失"
            return res.toJSONString()
        }
        val specialization = jsonObject["specialization"] as String?
        val version = jsonObject["version"] as String?
        val name = jsonObject["name"] as String?
        val content = jsonObject["content"] as String?
        if (StringUtils.isEmpty(specialization, version, name, content)) {
            res["code"] = 1
            res["msg"] = "specialization,version,name或content参数缺失"
            return res.toJSONString()
        }

        return if (cultivatingGoalPLService.addGraduationRequirement(specialization!!, version!!, name!!, content!!)) {
            res["code"] = 0
            res["msg"] = "success"
            res.toJSONString()
        } else {
            res["code"] = 3
            res["msg"] = "fail"
            res.toJSONString()
        }
    }


    /**
     * 指标点要求
     */

    @DeleteMapping("/indicator")
    fun delRequirementIndicator(id: Int?):String{
        val res = JSONObject()
        if (id==null) {
            res["code"] = 1
            res["msg"] = "id参数缺失"
            return res.toJSONString()
        }

        if (cultivatingGoalPLService.delRequirementIndicator(id!!)) {
            res["code"] = 0
            res["msg"] = "success"
        } else {
            res["code"] = 2
            res["msg"] = "fail"
        }
        return res.toJSONString()

    }


    @PatchMapping("/indicator")
    fun updateRequirementIndicator(indicatorId:Int?,content: String?):String{
        val res = JSONObject()
        if (StringUtils.isEmpty(content)||indicatorId==null) {
            res["code"] = 1
            res["msg"] = "indicatorId或content参数缺失"
            return res.toJSONString()
        }

        if (cultivatingGoalPLService.updateRequirementIndicator(indicatorId!!, content!!)) {
            res["code"] = 0
            res["msg"] = "success"
        } else {
            res["code"] = 2
            res["msg"] = "fail"
        }
        return res.toJSONString()
    }

    @PostMapping("/indicator")
    fun addRequirementIndicator(@RequestBody jsonObject: JSONObject?): String {
        val res = JSONObject()
        if (jsonObject == null) {
            res["code"] = 2
            res["msg"] = "参数缺失"
            return res.toJSONString()
        }
        val requirementId = jsonObject["requirementId"] as Int?
        val indicatorId = jsonObject["indicatorId"] as Int?
        val content = jsonObject["content"] as String?
        if (StringUtils.isEmpty(content)||indicatorId==null||requirementId==null) {
            res["code"] = 1
            res["msg"] ="requirementId,indicatorId或content参数缺失"
            return res.toJSONString()
        }

        return if (cultivatingGoalPLService.addRequirementIndicator(requirementId!!, indicatorId!!,  content!!)) {
            res["code"] = 0
            res["msg"] = "success"
            res.toJSONString()
        } else {
            res["code"] = 3
            res["msg"] = "fail"
            res.toJSONString()
        }

    }


    /**
     *课程体系对毕业要求的支撑关系表
     */

    @DeleteMapping("/course")
    fun delIndicatorCourse(indicatorId: Int?,courseSysId:String?):String{
        val res = JSONObject()
        if (indicatorId==null||StringUtils.isEmpty(courseSysId)) {
            res["code"] = 1
            res["msg"] = "indicatorId或courseSysId参数缺失"
            return res.toJSONString()
        }

        if (cultivatingGoalPLService.delIndicatorCourseByIndicatorIdAndCourseSysId(indicatorId!!,courseSysId!!)) {
            res["code"] = 0
            res["msg"] = "success"
        } else {
            res["code"] = 2
            res["msg"] = "fail"
        }
        return res.toJSONString()

    }

    @PatchMapping("/course")
    fun updateIndicatorCourse(indicatorId:Int?,courseSysId:String?,intensity: Double?):String{
        val res = JSONObject()
        if (StringUtils.isEmpty(courseSysId)||indicatorId==null) {
            res["code"] = 1
            res["msg"] = "indicatorId或courseSysId参数缺失"
            return res.toJSONString()
        }

        //这里的intensity怎样进行处理
        if (cultivatingGoalPLService.updateIndicatorCourse(indicatorId!!,courseSysId!!,intensity!!)) {
            res["code"] = 0
            res["msg"] = "success"
        } else {
            res["code"] = 2
            res["msg"] = "fail"
        }
        return res.toJSONString()
    }

    @PostMapping("/course")
    fun addSingleIndicatorCourse(@RequestBody jsonObject: JSONObject?): String {
        val res = JSONObject()
        if (jsonObject == null) {
            res["code"] = 1
            res["msg"] = "indicatorId,courseSysId或intensity参数缺失"
            return res.toJSONString()
        }
        val indicatorId = jsonObject["indicatorId"] as Int?
        val courseSysId = jsonObject["courseSysId"] as String?
        val intensity = jsonObject["intensity"] as Double?
        if (StringUtils.isEmpty(courseSysId)||indicatorId==null) {
            res["code"] = 1
            res["msg"] ="indicatorId或courseSysId参数缺失"
            return res.toJSONString()
        }

        //如果课程已存在，那就不才能重复添加  这个似乎没有进行判断  是在前端进行判断吗

        return if (cultivatingGoalPLService.addSingleIndicatorCourse(indicatorId!!, courseSysId!!, intensity!!)) {
            res["code"] = 0
            res["msg"] = "success"
            res.toJSONString()
        } else {
            res["code"] = 3
            res["msg"] = "fail"
            res.toJSONString()
        }

    }


    /**
     * 课程大纲上传  详见https://www.jb51.net/article/145500.htm
     */

//    @Deprecated("写错了，应该为文件的下载")
//    @PostMapping("/uploadingCourseSyllabus")
//    fun uploadingCourseSyllabus(@RequestParam("file") file: MultipartFile):String {
//        val res = JSONObject();
//        //判断文件是否为空
//        if (file.isEmpty) {
//            res["code"]=1
//            res["msg"]="文件为空"
//            return res.toJSONString()
//        }
//
//        /**
//         * 设置文件的存储路径
//         */
//
//        // 获取文件名
//        val fileName = file.originalFilename
//        UserService.logger.info("上传的文件名为：$fileName")
//        // 获取文件的后缀名
//        val suffixName = fileName!!.substring(fileName!!.lastIndexOf("."))
//        UserService.logger.info("文件的后缀名为：$suffixName")
//
//        // 设置文件存储路径
//        val classpath = ClassUtils.getDefaultClassLoader()?.getResource("")?.path.toString()
////        val dateTime = LocalDateTime.now()
////        val formattedTime = DateTimeFormatter.ofPattern(" yyyy-MM-dd-HHmm").format(dateTime)
////        val path = classpath + "generatedFile" + File.separator + fileName + formattedTime +suffixName
//        val path = classpath + "generatedFile" + File.separator + fileName + suffixName
//
//        //文件保存
//        val f=fileService.uploadingSyllabus(file,path)
//        if (f){
//            res["code"]=0
//            res["msg"]="success"
//            return res.toJSONString()
//        }else{
//            res["code"]=2
//            res["msg"]="fail"
//            return res.toJSONString()
//        }
//    }


    /**
     * 课程大纲的下载   这个apifox应该怎样写
     */
//    @GetMapping("/downloadCourseSyllabus")
//    fun downloadCourseSyllabus(fileName:String):String{
//        //获取文件的路径
//
//        //课程大纲应该需要写到数据库中，从数据库中查找并返回
//        val classpath = ClassUtils.getDefaultClassLoader()?.getResource("")?.path.toString()
//        val path = classpath + "generatedFile" + File.separator + fileName
//        val res = JSONObject();
//        try {
//            //文件查找与返回
//            val file = File(path)
//            // 检测是否存在目录
//            if (!file.getParentFile().exists()) {
//                res["code"]=1
//                res["msg"]="文件不存在"
//                return res.toJSONString()
//            }
//            res["code"]=0
//            res["msg"]="success"
//            res["file"]=file
//            return res.toJSONString();
//        } catch (e: IllegalStateException) {
//            e.printStackTrace()
//        } catch (e: IOException) {
//            e.printStackTrace()
//        }
//        res["code"]=2
//        res["msg"]="fail"
//        return res.toJSONString()
//
//    }


    @GetMapping("/downloadCourseSyllabus")
    fun downloadCourseSyllabus(id:Int?):ResponseEntity<ByteArray>?{
        if (id==null) {
            return null
        }
        val path=cultivatingGoalPLService.findFilename(id!!)

        //文件查找与返回
        val file = File(path)

        try {
            // 检测是否存在目录
            if (!file.getParentFile().exists()) {
                return null
            }
        } catch (e: IllegalStateException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }


        //设置响应头
        val headers = HttpHeaders().apply {

            setContentDispositionFormData("attachment", "课程大纲")
            contentType = MediaType.APPLICATION_OCTET_STREAM
        }

        return try {
            ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK)
        } catch (e: Exception) {
            e.printStackTrace()
            ResponseEntity<ByteArray>(e.message?.encodeToByteArray(), HttpStatus.EXPECTATION_FAILED)
        }
    }


    /**
     * 课程大纲的审核
     */

    @PostMapping("/courseAudit")
    fun  courseAudit(@RequestBody jsonObject: JSONObject?):String{
        val res=JSONObject()
         if(jsonObject==null){
             res["code"]=1
             res["msg"]="参数为空"
             return res.toJSONString()
         }

        val id = jsonObject["id"] as Int?
        val status=jsonObject["status"] as Int?
        val auditTeacherId=jsonObject["auditTeacherId"] as String
        val auditorsComment=jsonObject["auditorsComment"] as String



        if(id==null||status==null||StringUtils.isEmpty(auditTeacherId,auditorsComment)){
            res["code"]=1
            res["msg"]="参数为空"
            return res.toJSONString()
        }
        val auditedDate = LocalDate.now()
        cultivatingGoalPLService.updateAuditTeacherByID(id,status,auditTeacherId,auditTeacherId,auditedDate)

        res["code"]=0
        res["msg"]="success"
        return res.toJSONString()

    }


    /**
     * 试卷的下载
     */

    @GetMapping("/downloadTestAudit")
    fun downloadTestAudit(id:Int?):ResponseEntity<ByteArray>?{
        if (id==null) {
            return null
        }
        val path=cultivatingGoalPLService.findFilename(id!!)

        //文件查找与返回
        val file = File(path)

        try {
            // 检测是否存在目录
            if (!file.getParentFile().exists()) {
                return null
            }
        } catch (e: IllegalStateException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        //这个实在不会写

        //设置响应头
        val headers = HttpHeaders().apply {
            setContentDispositionFormData("attachment", "试卷审核表")
            contentType = MediaType.APPLICATION_OCTET_STREAM
        }

        return try {
            ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK)
        } catch (e: Exception) {
            e.printStackTrace()
            ResponseEntity<ByteArray>(e.message?.encodeToByteArray(), HttpStatus.EXPECTATION_FAILED)
        }
    }


    /**
     * 试卷审核
     */

    @PostMapping("/testAudit")
    fun  testAudit(@RequestBody jsonObject: JSONObject?):String{
        val res=JSONObject()
        if(jsonObject==null){
            res["code"]=1
            res["msg"]="参数为空"
            return res.toJSONString()
        }

        val id = jsonObject["id"] as Int?
        val status=jsonObject["status"] as Int?
        val auditTeacherId=loginService.currentUserId
        val auditorsComment=jsonObject["auditorsComment"] as String

        if(id==null||status==null||StringUtils.isEmpty(auditTeacherId,auditorsComment)){
            res["code"]=1
            res["msg"]="参数为空"
            return res.toJSONString()
        }
        val auditedDate = LocalDate.now()
        cultivatingGoalPLService.updateAuditTeacherByID(id,status,auditTeacherId!!,auditorsComment,auditedDate)

        res["code"]=0
        res["msg"]="success"
        return res.toJSONString()

    }




    /**
     * 课程组的创建
     *首先需要返回每一个课程  和每一个每一位老师   这个返回课程和老师的接口应该写了 只用进行下一步就行了
     * 在数据库中查询之后进行创建    这个需要进行两次请求
     */
    @PostMapping("/courseGroupCreate")
    fun courseGroupCreate(@RequestBody jsonObject: JSONObject?):String{
        val res=JSONObject();
        if (jsonObject == null) {
            res["code"] = 1
            res["msg"] = "name,teacherId或courseId参数缺失"
            return res.toJSONString()
        }
        val name = jsonObject["name"] as String?
        val courseId = jsonObject["courseId"] as String?
        val teacherId = jsonObject["teacherId"] as Int?
        if (StringUtils.isEmpty(name,courseId)||teacherId==null) {
            res["code"] = 2
            res["msg"] ="name,teacherId或courseId参数缺失"
            return res.toJSONString()
        }

        val createTime = LocalDate.now()


        if(courseGroupService.courseGroupCreate(name!!,courseId!!,teacherId,createTime)){
            res["code"] = 0
            res["msg"] ="success"

        }else{
            res["code"] = 3
            res["msg"] ="fail"
        }

        return res.toJSONString()

    }



}